﻿using Autofac;
using LIU.Framework.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LIU.Framework
{
    public class AppInstance
    {

        /// <summary>
        /// 注册类
        /// </summary>
        private ContainerBuilder Builder;

        /// <summary>
        /// 是否构造完成
        /// </summary>
        private bool isBuilded;

        /// <summary>
        /// ioc上下文
        /// </summary>
        private IComponentContext context;

        /// <summary>
        /// 程序集查找器
        /// </summary>
        public IFinder Finder { get; private set; }

        /// <summary>
        /// 依赖注入容器
        /// </summary>
        public IContainer Container { get; private set; }


        /// <summary>
        /// 构造函数
        /// </summary>
        protected AppInstance()
        { }

        /// <summary>
        /// 当前实例 每个程序只能有一个实例
        /// </summary>
        private static AppInstance current;

        /// <summary>
        /// 当前实例
        /// </summary>
        public static AppInstance Current
        {
            get { return current ?? (current = new AppInstance()); }
        }

        /// <summary>
        /// 设置实例
        /// </summary>
        /// <typeparam name="T">需要继承AppInstance</typeparam>
        /// <returns></returns>
        public static AppInstance Set<T>() where T : AppInstance, new()
        {
            if (typeof(T) == typeof(AppInstance))
            {
                return current = new AppInstance();
            }
            else
            {
                return current = new T();
            }
        }

        /// <summary>
        /// 初始化实例 
        /// </summary>
        /// <param name="finder"></param>
        /// <returns></returns>
        public AppInstance Init(IFinder finder)
        {
            this.Finder = finder;
            this.Builder = this.Builder ?? new ContainerBuilder();


            return this;
        }

        /// <summary>
        /// 自定义注入配置
        /// </summary>
        /// <param name="action">委托方法</param>
        /// <returns></returns>
        public AppInstance Config(Action<ContainerBuilder> action)
        {
            action.Invoke(this.Builder);
            return this;
        }

        /// <summary>
        /// 构建实例
        /// </summary>
        public void Build()
        {
            this.Container = Builder.Build();
            this.Container.Resolve<IComponentContext>();
        }
    }
}
